import { Injectable, signal } from '@angular/core';
import { SheQu } from '../models/shequ.model';
import { tap, of, Observable } from 'rxjs';
import { DUMMY_SHEQU } from './shequ';
import { MyBaseService } from './mybaseservice.service';


@Injectable({
  providedIn: 'root'
})
export class ShequService extends MyBaseService {
  private _allSheQu = signal<SheQu[]>([]);

  get allSheQu() {
    return this._allSheQu.asReadonly();
  }


  constructor() {
    super();
    //如果不启动后端，请加载假数据
    this._allSheQu.set(DUMMY_SHEQU as SheQu[]);
  }

  getAllSheQu(): Observable<SheQu[]> {
    return this.httpClient.get<SheQu[]>(this.backendURL + "/shequ/all").pipe(//后端获取数据后，本地_allSheQu更新数据
      tap({
        next: (data) => this._allSheQu.set(data),
        error: (error: Error) => {
          console.log(error.message);
          return of([]);
        }
      })
    );
  }

  getSheQuByID(shequID: string): Observable<SheQu> {
    return this.httpClient.get<SheQu>(this.backendURL + '/shequ/' + shequID);
  }

  createSheQu(postSheQu: SheQu): Observable<SheQu> {
    return this.httpClient.post<SheQu>(this.backendURL + '/shequ', postSheQu).pipe(//后端成功添加后，本地_allSheQu更新数据
      tap({
        next: (data) => {
          this._allSheQu.update(previewArray => [...previewArray, data]);
        }
      })
    );
  }

  updateSheQu(putSheQu: SheQu) {
    return this.httpClient.put<SheQu>(this.backendURL + '/shequ', putSheQu).pipe(//后端成功更新数据后，本地_allSheQu更新数据
      tap({
        next: (data) => {
          this._allSheQu.update(previewArray => {
            const index = previewArray.findIndex(item => item.sheQuID === data.sheQuID);
            if (index !== -1) {
              previewArray[index] = data;
            }
            return previewArray;
          });
        }
      })
    );
  }

  deleteSheQu(shequID: string) {
    return this.httpClient.delete(this.backendURL + '/shequ/' + shequID).pipe(//后端成功删除后，本地_allSheQu更新数据
      tap({
        next: (data) => {
          this._allSheQu.update(previewArray => previewArray.filter(item => item.sheQuID !== shequID));
        }
      })
    );
  }
}
